package dbops

import "gitee.com/DengAnbang/goutils/dbutils"

func ListSession() ([]string, error) {
	stmtOut, err := dbConn.Prepare(`SELECT sessions.session FROM sessions `)
	if err != nil {
		return nil, err
	}
	rows, err := stmtOut.Query()
	if err != nil {
		return nil, err
	}
	var strings map[string]string
	res := make([]string, 0)
	for rows.Next() {
		strings, err = dbutils.GetRowsMap(rows)
		if err != nil {
			continue
		}
		res = append(res, strings["session"])
	}
	return res, nil
}
func AddSession(sid, uid, session string) (error) {
	stmtIn, err := dbConn.Prepare(`INSERT INTO sessions
		(session_id,user_id,session)VALUES(?,?,?)`)
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(sid, uid, session)
	stmtIn.Close()
	return err
}
func DeleteSession(sid string) (error) {
	stmtIn, err := dbConn.Prepare(`DELETE FROM sessions WHERE session_id = ?`)
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(sid)
	stmtIn.Close()
	return err
}
func GetSessionIdByUserId(uid string) (string, error) {
	stmtOut, err := dbConn.Prepare(`SELECT sessions.session_id FROM sessions WHERE user_id = ?`)
	if err != nil {
		return "", err
	}
	rows, err := stmtOut.Query(uid)
	if err != nil {
		return "", err
	}

	for rows.Next() {
		strings, err := dbutils.GetRowsMap(rows)
		if err != nil {
			continue
		}
		return strings["session_id"], nil
	}
	return "", nil
}